//
//  DYZixunViewController.swift
//  SheYangBigData
//
//  Created by 宋海胜 on 2020/12/31.
//  Copyright © 2020 叁拾叁. All rights reserved.
//

import UIKit
import MJRefresh
import RxSwift
import RxDataSources
import Then
import SDCycleScrollView

enum DYZixunListType {
    case zhusu
    case jingqu
    case meishi
}

class DYZixunViewController: SYBaseTableViewController {
    
    var searchView: DYSearchView!
    fileprivate var choiceView: VGBaseChoiceView<VGBaseChoiceOrgModel, VGChoiceNormalCell>!
    fileprivate var vm: VGTableViewPageViewModel<DYZixunListModel>!
    var zixunModel: DYZixunModel!
    var listType: DYZixunListType!
    var params: [String: String] = [:] {
        didSet {
            self.getList()
        }
    }
    
    init(model: DYZixunModel, listType: DYZixunListType) {
        super.init(nibName: nil, bundle: nil)
        self.listType = listType
        self.zixunModel = model
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setSearchView()
        setTableView()
        setNoDataView()
        setupViewModel()
        self.title = "全部咨询"
    }
    
    fileprivate func setupViewModel() {
        vm = VGTableViewPageViewModel<DYZixunListModel>()
        vm.tableView = tableView
        vm.emptyViewParams = ("", "", 40.0, 30.0)
        tableView.vg_pageProtocol = vm
        
        vm.loadDataClosure = {[weak self] success in
            if let `self` = self {
                if success {
                    self.loadDataSuccessed()
                }
            }
        }
        
        vm.getDataClosure = {[weak self] page in
            if let `self` = self {
                self.getList()
            }
        }
        
        getList()
    }
    
    func getList() {
        
        switch listType {
        case .zhusu:
            vm.getList(type: .dy_zhusuZhixunList(page: 1, size: 10, dic: self.params), dispose: dispose)
        case .jingqu:
            vm.getList(type: .dy_jingquZhixunList(page: 1, size: 10, dic: self.params), dispose: dispose)
        case .meishi:
            vm.getList(type: .dy_meishiZhixunList(page: 1, size: 10, dic: self.params), dispose: dispose)
            
        default:
            break
        }
    }
    
    func loadDataSuccessed() {
        DispatchQueue.main.async {
            
            self.setDataSource()
        }
    }
    
    func setSearchView() {
        searchView = DYSearchView(frame: CGRect.init(x: 0, y: NAV_HEIGHT, width: SCREEN_WIDTH, height: 49.0.autoWidth()))
        searchView.clickChoiceClosure = {[weak self] index in
            if let `self` = self {
                if index == 0 {
                    self.params = [:]
                } else {
                    self.params = ["issue":self.searchView.tf.text ?? ""]
                }
            }
        }
        view.addSubview(searchView)
        
        let zixun: UIButton = UIButton()
        zixun.addTarget(self, action: #selector(zixunAction), for: .touchUpInside)
        zixun.backgroundColor = UIColor(hex: 0x367FF6)
        zixun.setTitle("我要咨询", for: .normal)
        zixun.setTitleColor(UIColor.white, for: .normal)
        zixun.titleLabel?.font = 18.autoFontSize()
        view.addSubview(zixun)
        zixun.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().offset(-BOTTOM_SAFE_HEIGHT)
            make.left.right.equalToSuperview()
            make.height.equalTo(44.autoWidth())
        }
    }
    
    func setTableView() {
        
        //创建表格视图
        self.tableView = UITableView(frame: CGRect(x: 0, y: NAV_HEIGHT+49.0.autoWidth(), width: SCREEN_WIDTH, height: SCREEN_HEIGHT-NAV_HEIGHT-93.0.autoWidth()-BOTTOM_SAFE_HEIGHT), style:.plain)
        self.tableView.separatorStyle = .none
        self.tableView.backgroundColor = UIColor(hex: 0xF2F2F2)
        self.tableView!.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        self.view.addSubview(self.tableView!)
        
        tableView.rx.itemSelected
            .subscribe(onNext:{ [weak self] indexPath in
                if let `self` = self {
                    
                }
            })
            .disposed(by:dispose)
    }
    
    func setNoDataView() {
        noDataView = SYNoDataView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-NAV_HEIGHT))
        noDataView.isHidden = true
        tableView.addSubview(noDataView)
    }
    
    func setDataSource() {
        //初始化数据
        let sections = Observable.just([
            DYZixunListSection(header: "", items: self.vm.dataSource)
        ])
        
        //创建数据源
        let dataSource = RxTableViewSectionedAnimatedDataSource<DYZixunListSection>(
            //设置单元格
            configureCell: { ds, tv, ip, item in
                
                
                let cell: DYZixunCell = tv.dequeueReusableCell(withIdentifier: "Cell")
                    as? DYZixunCell ?? DYZixunCell(style: .default, reuseIdentifier: "Cell")
                cell.configureView(item)
                cell.selectionStyle = .none
                return cell
                
                
            },
            //设置分区头标题
            titleForHeaderInSection: { ds, index in
                return ds.sectionModels[index].header
            })
        tableView.dataSource = nil
        //绑定单元格数据
        sections
            .bind(to: tableView.rx.items(dataSource: dataSource))
            .disposed(by: dispose)
        
    }
    
    @objc func zixunAction() {
        let vc = DYZixunInputViewController(model: self.zixunModel)
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    
}


extension DYZixunViewController: SDCycleScrollViewDelegate {
    
    func cycleScrollView(_ cycleScrollView: SDCycleScrollView!, didSelectItemAt index: Int) {
        print("选择了轮播图\(index)")
    }
}


//自定义Section
struct DYZixunListSection {
    var header: String
    var items: [Item]
}

extension DYZixunListSection : AnimatableSectionModelType {
    typealias Item = DYZixunListModel
    
    var identity: String {
        return header
    }
    
    init(original: DYZixunListSection, items: [Item]) {
        self = original
        self.items = items
    }
}

extension DYZixunListModel: IdentifiableType {
    var identity: String {
        return id!
    }
    
    typealias Identity = String
}
